from types import NoneType
import cv2
import numpy as np
from astropy.table.bst import MaxValue, MinValue

capture = cv2.VideoCapture(1)  # 打开笔记本内置摄像头
while (capture.isOpened()):  # 笔记本内置摄像头被打开后
    retval, image = capture.read()  # 从摄像头中实时读取视频
    img = image.copy()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #转化为灰度图
    gray = cv2.GaussianBlur(gray, (7, 7), 0) #高斯滤波


    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 30, param1=75, param2=75, minRadius=1, maxRadius=300) #HoughCircles识别，返回x，y，以及圆的半径

    gray = cv2.Canny(gray,20,100) #对于图像进行边缘检测，min和max之间的值越小对于细节保存越多

    contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #找到轮廓

    if type(circles) != type(None):     #防止没有找到圆形轮廓

        circles = np.uint16(np.around(circles))

        for i in circles[0,:]:
            cv2.circle(img, (i[0],i[1]),i[2],(0,255,0),2)  #draw the circle
            cv2.circle(img, (i[0],i[1]),2,(0,0,255),3)

    cv2.imshow("Video", img)  # 在窗口中显示读取到的视频
    key = cv2.waitKey(1)  # 窗口的图像刷新时间为1毫秒
    if key == 27:  # 如果按下esc
        break
capture.release()  # 关闭笔记本内置摄像头
cv2.destroyAllWindows()  # 销毁显示摄像头视频的窗口


